<template>
  <el-dialog
    :title="row.id ? '修改学科' : '新增学科'"
    :visible.sync="dialogVisible"
    width="21%"
    :before-close="handleClose"
    center
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="学科名称" prop="name" size="small">
        <el-input
          v-model.trim="form.name"
          placeholder="请输入学科名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="是否显示" prop="show">
        <el-switch
          v-model="form.show"
          active-color="#13ce66"
          inactive-color="#ff4949"
        ></el-switch>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 认</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { addSubject, reviseSubject } from '@/api/hmmm/subjects'

export default {
  name: 'SubjectsAdd',
  data () {
    return {
      dialogVisible: false,
      form: {
        name: '',
        show: true
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入学科名称',
            trigger: 'blur'
          }
        ]
      },
      row: {}
    }
  },
  methods: {
    onSubmit () {
      this.$refs.form.validate(async valid => {
        if (valid) {
          if (!this.row.id) {
            try {
              await addSubject({
                subjectName: this.form.name,
                isFrontDisplay: this.form.show ? 1 : 0
              })
              this.$message.success('添加成功')
              this.$emit('getSubjects')
            } catch (err) {
              this.$message.error('添加失败，请重试')
            }
          } else {
            try {
              await reviseSubject({
                id: this.row.id,
                isFrontDisplay: this.form.show,
                subjectName: this.form.name
              })
              this.$message.success('修改成功')
              this.row = {}
              this.$emit('getSubjects')
            } catch (err) {
              this.$message.error('修改失败，请重试')
            }
          }
          this.form.name = ''
          this.form.show = true
          // this.$refs.form.resetFields()
          this.dialogVisible = false
        }
      })
    },
    onRevise (row) {
      this.dialogVisible = true
      this.form.name = row.subjectName
      this.form.show = row.isFrontDisplay === 1
      this.row = row
    },
    handleClose () {
      this.$refs.form.resetFields()
      this.dialogVisible = false
      this.form.name = ''
      this.form.show = true
      this.row = {}
    }

  }
}
</script>

<style scoped lang='less'></style>
